import React from 'react'
import { Tooltip, Space } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheButton from "@/components/TheButton";
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend';
import TheImage from '@/components/TheImage';
import { goodsClassifyList } from '@/request/storeBackManage/goodsManage/centerGoodsList';
import { goodsBankInfoPage, goodsBankUpdateState } from '@/request/storeBackManage/goodsManage/goodsBank';
import store from "@/store/store"
import _ from 'lodash';
import { getDateTime3 } from '@/utils/getDate'
import { exportSheetTable } from '@/utils/exportTable'

export default class App extends React.Component {
  constructor() {
    super()
    this.SelfSupportShopTableRef = React.createRef()
    this.state = {
      columns: [
        {
          title: "商品ID",
          dataIndex: "goodsId",
          key: "goodsId",
          width: 200,
        },
        {
          title: "商品名称",
          dataIndex: "goodsName",
          key: "goodsName",
          width: 300,
        },
        {
          title: "商品图片",
          dataIndex: "goodsShowImages",
          key: "goodsShowImages",
          width: 200,
          render: (text, record) => {
            return <TheImage src={record.goodsShowImages.split(',')[0]} width={80} height={80} />
          }
        },
        {
          title: "所属类目",
          dataIndex: "goodsClassifyName",
          key: "goodsClassifyName",
          width: 200,
        },
        {
          title: "日常价",
          dataIndex: "currentPrice",
          key: "currentPrice",
          width: 200,
          render: (text, record) => {
            return record.currentPriceMax === record.currentPriceMin ? <React.$Price price={record.currentPriceMax || 0} /> : <div>
              <React.$Price price={record.currentPriceMin || 0} /> ~<React.$Price price={record.currentPriceMax || 0} />
            </div>

          }
        },
        {
          title: "划线价",
          dataIndex: "originalPrice",
          key: "originalPrice",
          width: 200,
          render: (text, record) => {
            return record.originalPriceMax === record.originalPriceMin ? <React.$Price price={record.originalPriceMax || 0} /> : <div>
              <React.$Price price={record.originalPriceMin || 0} /> ~<React.$Price price={record.originalPriceMax || 0} />
            </div>
          }
        },
        {
          title: "审核状态",
          dataIndex: 'reviewStatus',
          key: 'reviewStatus',
          width: 200,
          render: (text, record) => {
            let label = ''
            switch (text) {
              case 'D':
                label = '待审核'
                break
              case 'B':
                label = (
                  <div>
                    <span style={{ marginRight: 20 }}>已驳回</span>
                    <Tooltip title={record.dismissReason}>
                      <QuestionCircleOutlined />
                    </Tooltip>
                  </div>
                )
                break
            }
            return label
          }
        },
        {
          title: "创建时间",
          dataIndex: "updateTime",
          key: "updateTime",
          width: 200,
          render: (text, record) => {
            return record.updateTime ? record.updateTime : "/"
          }
        },
        {
          title: "上次操作时间",
          dataIndex: "lastUpdateTime",
          key: "lastUpdateTime",
          width: 200,
          render: (text, record) => {
            return record.lastUpdateTime ? record.lastUpdateTime : "/"
          }
        },
        {
          title: "操作人",
          dataIndex: "userName",
          key: "userName",
          width: 200,
          render: (text, record) => {
            return record.userName ? record.userName : "/"
          }
        },
        {
          title: "操作",
          fixed: "right",
          width: 200,
          render: (text, record) => {
            return (
              <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center', alignItems: 'center' }}>
                <TheButton haspermi={['goodsManage:centerGoodsList:release']} onClick={() => this.releaseGoods([record.goodsId])}>发布</TheButton>
                <TheButton haspermi={['goodsManage:centerGoodsList:details']} onClick={() => { this.props.history.push(`/goodsManage/centerGoodsList/detail/${record.goodsId}`); }}>查看详情</TheButton>
                <TheButton hasPermi={['goodsManage:centerGoodsList:edit']} onClick={() => this.props.history.push(`/goodsManage/centerGoodsList/editGoods/${record.goodsId}`)}>编辑</TheButton>
              </div>
            );
          },
        },
      ],
      form_show: true,
      searchOption: [
        {
          field: 'goodsName',
          label: '商品名称',
          placeholder: '商品名称',
          type: 'Input',
        },
        {
          field: 'goodsId',
          label: '商品ID',
          placeholder: '商品ID',
          type: 'Input',
          rules: [{ pattern: /^[0-9]+$/, message: '只能输入数字' }]
        },
        {
          field: 'searchMaterialId',
          label: '物料ID',
          placeholder: '物料ID',
          type: 'Input',
        },
        {
          field: 'classifyId',
          label: '所属类目',
          placeholder: '全部',
          type: 'Select',
          api: goodsClassifyList,
          txt: 'goodsClassifyName',
          value: 'goodsClassifyId',
          params: { level: 2 },
          options: [],
        },
        { field: 'time', label: '创建时间', type: 'RangePicker' },
      ],
      queryForm: {},
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 1,
      isModal: false,//同步商品弹窗
      loading: false,//确认同步商品按钮loading
      selectedRowKeys: [],
      dataSource: [],
      exportLoading: false,//导出loading
    }
  }
  componentDidMount() {
    this.onColumnsFilter(this.state.columns)
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, pathName } = searchParams
    if (searchParams && pageNo && pathName == 'goodsBank') {
      this.setState({
        queryForm, pageData: { pageNo, pageSize }
      }, () => {
        this.queryFormRef.onSetDefault({ ...queryForm })
        this.getData(queryForm)
      })
    } else {
      this.getData(this.state.queryForm)
    }
  }
  // 获取数据
  getData = (values) => {
    if (values && !_.isEmpty(values.time)) {
      values.createTimeStart = getDateTime3(values.time[0])
      values.createTimeEnd = getDateTime3(values.time[1])
      delete values.time
    }
    let { pageData: { pageNo, pageSize }, queryForm } = this.state
    this.setState({
      queryForm: values === undefined ? queryForm : { ...values }
    }, async () => {
      const params = { pageNo, pageSize, ...this.state.queryForm, reviewStatusList: ["D", "B"] }
      store.dispatch({
        type: 'SaveSearchValues',
        data: { pathName: 'goodsBank', ...params }
      })
      let res = await goodsBankInfoPage({ ...params })
      if (res.code === 0 && res.data) {
        this.setState({
          dataSource: res.data,
          synchronousGoodsDataSource: [],
          pageData: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          total: res.totalCount
        })
      }
    })
  }
  // 搜素
  onFormSearch = (values) => {
    this.setState({ pageData: { pageNo: 1, pageSize: 10 } }, () => { this.getData(values) })
  }
  // 搜索重置
  onReset = () => {
    this.setState({
      queryForm: {}
    }, () => { this.pageChange(1, 10) })
  }
  // 重新渲染表格
  onColumnsFilter(value) {
    this.setState({
      newColumns: value
    })
  }
  // 切换分页
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: { pageNo, pageSize }
    }, () => { this.getData() })
  }
  // 发布商品
  releaseGoods = (goodsId) => {
    React.$confirm({
      title: '您确定发布此商品吗？',
      onOk: async () => {
        let response = await goodsBankUpdateState({ goodsId, reviewStatus: 'S' })
        if (response.code === 0) {
          React.$message({ type: 'info', content: '发布成功' })
          this.getData()
        }
      }
    })
  }
  // 导出商品
  exportGoods = async () => {
    this.setState({ exportLoading: true })
    let res = await goodsBankInfoPage({ pageNo: 1, pageSize: 99999, ...this.state.queryForm, reviewStatusList: ["D", "B"] })
    if (res.code === 0 && res.data) {
      let tB_data = []
      let tH_data = [
        { prop: 'goodsId', title: '商品ID' },
        { prop: 'goodsName', title: '商品名称' },
        { prop: 'goodsClassifyName', title: '所属类目' },
        { prop: 'originalPrice', title: '日常价', valueType: 'number' },
        { prop: 'currentPrice', title: '划线价', valueType: 'number' },
        { prop: 'shenhestatus', title: '审核状态' },
        { prop: 'updateTime', title: '创建时间' }]

      res.data.forEach(item => {
        let label = ''
        switch (item.reviewStatus) {
          case 'D':
            label = '待审核'
            break
          case 'B':
            label = '已驳回'
            break
        }
        tB_data.push({
          ...item,
          shenhestatus: label,
          originalPrice: item.currentPriceMax === item.currentPriceMin ? Number(item.currentPriceMax / 100).toFixed(2) :
            `${Number(item.currentPriceMin / 100).toFixed(2)} ~ ${Number(item.currentPriceMax / 100).toFixed(2)}`
          ,
          currentPrice: item.originalPriceMax === item.originalPriceMin ? Number(item.originalPriceMax / 100).toFixed(2) :
            `${Number(item.originalPriceMin / 100).toFixed(2)} ~ ${Number(item.originalPriceMax / 100).toFixed(2)}`
          ,
        })
      })
      this.setState({ exportLoading: false })
      exportSheetTable({ fileName: '商品库列表', tH_data, tB_data, isSheet: true, sheetSize: 1000 })
    }
  }
  render() {
    let { form_show, searchOption, columns, newColumns, dataSource, pageData: { pageNo, pageSize }, total, exportLoading } = this.state
    return (
      <div className={'p-layout-box commodity-content'}>
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
          <TheButton hasPermi={['goodsManage:goodsBank:export']} style={{ marginRight: 10 }} type="default" size="module" onClick={() => { this.exportGoods() }} loading={exportLoading}>导出</TheButton>
        </TheQueryForm>
        <TheTableExtend
          columns={columns}
          onFormTrigger={() => this.setState({ form_show: !form_show })}
          onTableRefresh={() => this.getData()}
          onColumnsFilter={(value) => this.onColumnsFilter(value)}
        >
        </TheTableExtend>
        <TheTable
          scroll={{ x: "960", y: '61vh' }}
          columns={newColumns}
          dataSource={dataSource}
          rowKey={'goodsId'}
        />
        <ThePagination
          pageNo={pageNo}
          pageSize={pageSize}
          total={total}
          pageChange={this.pageChange}
        />
      </div>
    )
  }
}